<?php
class DB {
	private $server = 'localhost';
	private $user = 'root';
	private $password = '';
	private $dbName = 'log';
	private $link = false;
	private $debugFileName = 'debug.ignored.txt';
	
	public $debug_mode = false;
	
	public function __construct($auto_connect = true) {
		if($auto_connect)
			$this->connect();
	}
	
	public function connect() {
		$link = mysql_connect($this->server, $this->user, $this->password );
		if ($link != false) {
			$this->link = $link;
			//$this->debug('Connection: success;');
			if (mysql_select_db($this->dbName)) {
				$this->debug("Connection: success;\r\n".'Database selected: '.$this->dbName);
			}
		else{
			mysql_close($this->link);
			$this->link = false;
			$this->debug("Connection: success;\r\n".'While selected db \''. $this->dbName. '\' an error occure. '."\r\nConnection is closed.");
			}
		}
		else
			$this->debug('Connection: fail;\r\nError: '.mysql_error($link));
	}
	
	public function selectOne($query) {
		if ($this->isConnected()) {
			$this->debug($query);
			$res = mysql_query($query, $this->link);
			return mysql_fetch_array($res, MYSQL_ASSOC);
		}
		return false;
	}
	
	public function selectArray($query) {
		if ($this->isConnected()) {
			$res = mysql_query($query, $this->link);
			if ($res == false) {
				$this->debug("Wrong query: \r\n$query");
				return false;
			}
			$this->debug("SELECT OK:\r\n".$query);
			$arr = array();
			while (($row = mysql_fetch_array($res, MYSQL_ASSOC)) != false) {
				$arr[] = $row;
			}
			return $arr;
		}
		return false;
	}
	
	public function insert($table, $values) {
		if (	is_string($table) && 
				strlen($table)>0 && 
				is_array($values) && 
				!empty($values) && 
				$this->isConnected()) {
			$query = "INSERT INTO `$table` SET ";
			foreach ($values as $k => $v) {
				$query .= "`$k`=";
				if(is_integer($v))
					$query .= $v;
				else
					$query .= '\''.mysql_real_escape_string($v).'\'';
				//if (next($values))
					$query .= ', ';
			}
			$query[strlen($query) - 2] = ';';
			
			$this->debug("INSERT OK:\r\n".$query);
			mysql_query($query, $this->link);
		}
	}
	
	public function isConnected() {
		if ($this->link == false) {
			$this->debug('Not connected');
			return false;
		}
		return true;
	}
	
	private function debug($debug_str) {
		if ($this->debug_mode == true) {
			$out_str = "\r\n---------------------------------\r\n".$debug_str;
			file_put_contents($this->debugFileName, $out_str, FILE_APPEND);
		}
	}
}
?>